<template>
  <div class="view-container">

    <div class="main-content">
      <div class="list-container">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <div class="filter-container">
            <el-row :gutter="40" style="margin:0px;">
              <el-col :lg="24">
                <el-form :inline="true" :model="filterData" label-position="right" size="small"
                  class="filter-form-inline">
                  <el-row :gutter="40" style="margin-left: 0px; margin-right: 0px">
                    <el-col :lg="4" :xs="4">
                      <el-form-item label="审批类型" style="width: 100%">
                        <el-select v-model="filterData.processDefinitionKey" clearable style="width: 100%"
                          placeholder="请选择审批类型" @change="listSearch">
                          <el-option v-for="item in dictMap?.approval_type" :key="item.id" :label="item.label"
                            :value="item.value" />

                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :lg="4" :xs="4">
                      <el-form-item label="关键字" style="width: 100%">
                        <el-input v-model="filterData.keyWord" clearable placeholder="流程编号，信息摘要" />
                      </el-form-item>
                    </el-col>
                    <el-col :lg="4" :xs="4">
                      <el-form-item :label="label" style="width: 100%">
                        <date-range-picker v-model:date="date" style="width: 100%" type="daterange" range-separator="至"
                          start-placeholder="开始日期" end-placeholder="结束日期" @change="handlDate" />
                      </el-form-item>
                    </el-col>
                    <el-col v-if="activeName==='COMPLETED'" :lg="4" :xs="4">
                      <el-form-item label="状态" style="width: 100%">
                        <el-select v-model="filterData.taskConclusion" clearable style="width: 100%"
                          placeholder="请选择审批状态">
                          <el-option v-for="item in dictMap?.endtask" :key="item.id" :label="item.label"
                            :value="item.value" />

                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :lg="4" :xs="4">
                      <el-form-item label="发起人">
                        <el-select v-model="filterData.initiator" style="width: 100%" placeholder="请选择发起人">
                          <el-option v-for="item in headList" :key="item.id" :label="item.realName"
                            :value="item.userName" />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :lg="4" :xs="4">
                      <el-form-item style="width: 100%">
                        <el-button class="border-btn" @click="handlReact">重置</el-button>
                        <el-button type="primary" class="main-btn" @click="handlSearch">搜索</el-button>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
              </el-col>
            </el-row>
          </div>
          <el-tab-pane label="待处理" name="ACTIVE" />
          <el-tab-pane label="已处理" name="COMPLETED" />
        </el-tabs>
        <table-view header-cell-class-name="table-header" :data="listData" border :cell-style="cellStyle"
          @sort-change="handlSort" @row-click="rowClick">
          <el-table-column prop="processNo" label="流程编号" fixed="left" :min-width="140" header-align="center" />

          <el-table-column :min-width="180" prop="processDefinitionName" label="流程审批类型" header-align="center"
            :show-overflow-tooltip="true" />

          <el-table-column :min-width="450" prop="abstract" label="信息摘要" header-align="center"
            :show-overflow-tooltip="true" />

          <el-table-column label="发起人" header-align="center" align="center" :show-overflow-tooltip="true"
            :min-width="140">
            <template #default="scope">
              <span> {{ scope.row.initiator }}</span>
              <span v-if="scope.row.deptName">[{{ scope.row.deptName }}]</span>
            </template>
          </el-table-column>

          <el-table-column label="发起时间" sortable="custom" align="center" width="170">
            <template #default="scope">
              <span> {{ dateFormat('yyyy-mm-dd HH:MM:SS', scope.row.startTime) }}</span>
            </template>
          </el-table-column>

          <template v-if="filterData.status === 'ACTIVE'">
            <el-table-column label="进入步骤时间" align="center" width="170">
              <template #default="scope">
                <div v-if="scope.row.currentTask !== null" style="line-height: 20px">
                  {{ dateFormat('yyyy-mm-dd HH:MM:SS', scope.row.currentTask.startTime) }}
                </div>
                <div style="color:red;line-height: 20px"> {{ handlTime(scope.row.currentTask.startTime) }}</div>
              </template>
            </el-table-column>

            <el-table-column :min-width="140" label="当前审批节点" header-align="center" align="center">
              <template #default="scope">
                <!--                <div>-->
                <!--                  {{ scope.row.currentTask?.taskName }}-->
                <!--                </div>-->
                <div v-if="scope.row.currentTask?.taskAssignee">
                  <i class="iconfont icon-user" style="font-size:14px" />
                  <span style="margin-left:4px;">{{ scope.row.currentTask?.taskAssignee }}</span>
                </div>
              </template>
            </el-table-column>

            <el-table-column :min-width="100" label="状态" align="center" fixed="right">
              <template #default="scope">
                {{ getLabel('approval_result', scope.row.processInstanceConclusion) }}
              </template>
            </el-table-column>
            <el-table-column :min-width="140" label="操作" fixed="right" align="center">
              <template #default="scope">
                <el-button v-auth="{v:['crm:audit:myDealWith:undo'],bool:scope.row.whetherCancel}" type="text"
                  @click="cancelOperation(scope.row)">撤销
                </el-button>

                <el-button v-auth="{v:['crm:audit:myDealWith:approval'],bool:scope.row.currentTask?.allow}" type="text"
                  @click.stop="handlApproval(scope.row)">审批
                </el-button>
              </template>
            </el-table-column>
          </template>

          <template v-if="filterData.status === 'COMPLETED'">
            <el-table-column label="进入步骤时间" align="center" width="180">
              <template #default="scope">
                <span> {{ dateFormat('yyyy-mm-dd HH:MM:SS', scope.row.startTime) }}</span>
              </template>
            </el-table-column>

            <el-table-column label="处理时间" sortable="custom" align="center" width="180">
              <template #default="scope">
                <span> {{ dateFormat('yyyy-mm-dd HH:MM:SS', scope.row.endTime) }}</span>
              </template>
            </el-table-column>

            <el-table-column label="处理结论" width="120" align="center" fixed="right">
              <template #default="scope">
                {{ getLabel("approval_result", scope.row.taskConclusion) }}
              </template>
            </el-table-column>
          </template>

        </table-view>
        <Pagination v-model:page="filterData.page" v-model:limit="filterData.pageSize"
          style="display: flex; justify-content: flex-end" :total="total" @pagination="handlList" />
      </div>
      <approval-dialog ref="bouncedDialog" @succsess="succsess" />
    </div>
  </div>
</template>

<script>
import {getCurrentInstance, inject, onMounted, reactive, toRefs,} from "vue";
import {useRouter} from "vue-router";
import {crmStore} from "@CRM/store";

export default {
  setup(props, context) {
    const api = inject("api");
    const router = useRouter();
    const currentInstance = getCurrentInstance();
    var reactiveData = reactive({
      listData: [],
      total: 0,
      filterData: {
        status: "ACTIVE",
        processDefinitionKey: "",
        keyWord: "",
        page: 1,
        pageSize: 20,
        initiatorStartTime: null, // 发起开始时间
        initiatorEndTime: null, // 发起结束时间
        manageStartTime: null, // 处理开始时间
        manageEndTime: null, // 处理结束时间
        taskConclusion: "",
        initiator: "",
      },
      date: "",
      label: "发起时间",
      activeName: "ACTIVE",
      bouncedDialog: null,
      dictMap: crmStore.getters["dictionary/getDictionary"],
      headList: crmStore.getters["company/getHeadOptions"] || [],
    });

    // 鼠标样式
    const cellStyle = (row) => {
      if (row.column.label === "操作") return;
      return "cursor: pointer;";
    };

    const handlDate = (val) => {
      if (val) {
        if (reactiveData.activeName === "ACTIVE") {
          reactiveData.filterData.initiatorStartTime = val[0];
          reactiveData.filterData.initiatorEndTime = val[1];
        }
        if (reactiveData.activeName === "COMPLETED") {
          reactiveData.filterData.manageStartTime = val[0];
          reactiveData.filterData.manageEndTime = val[1];
        }
      }
    };
    // 获取负责人
    const handlHead = () => {
      api.terminal.HEAD_PEOPLE(1).then((res) => {
        if (res.code === 0) {
          reactiveData.headList = res.data;
        }
      });
    };

    // 点击跳转详情
    const rowClick = (row, column, event) => {
      console.log(row, column.label, event);
      if (column.label === "操作") return;
      const commit = {
        id: row.processInstanceId,
        type: row.processDefinitionKey,
        serviceKey: row.serviceKey,
        taskId: row?.currentTask?.taskId,
        xmlId: row?.processDefinitionId,
      };
      router.push({
        name: "myDealWithDetail",
        query: commit,
      });
    };

    const handlSearch = () => {
      reactiveData.filterData.page = 1;
      handlList();
    };

    const handlReact = () => {
      reactiveData.filterData = {
        status: reactiveData.activeName,
        processDefinitionKey: "",
        keyWord: "",
        page: 1,
        pageSize: 20,
        initiatorStartTime: null, // 发起开始时间
        initiatorEndTime: null, // 发起结束时间
        manageStartTime: null, // 处理开始时间
        manageEndTime: null, // 处理结束时间
        taskConclusion: "",
        initiator: "",
      };
      reactiveData.date = "";
      handlList();
    };

    // 切换tabs
    const handleClick = (tab, event) => {
      console.log(tab.props.name);
      reactiveData.date = "";
      reactiveData.filterData = {
        status: tab.props.name,
        keyWord: "",
        page: 1,
        pageSize: 20,
        initiatorStartTime: null, // 发起开始时间
        initiatorEndTime: null, // 发起结束时间
        manageStartTime: null, // 处理开始时间
        manageEndTime: null, // 处理结束时间
        processDefinitionKey: "",
      };
      reactiveData.activeName = tab.props.name;
      if (reactiveData.activeName === "ACTIVE") {
        reactiveData.label = "发起时间";
      }
      if (reactiveData.activeName === "COMPLETED") {
        reactiveData.label = "处理时间";
      }

      reactiveData.filterData.status = tab.props.name;
      handlList();
    };

    // 获取列表
    const handlList = () => {
      let commit;
      reactiveData.listData = [];
      if (reactiveData.activeName === "ACTIVE") {
        commit = api.myDealWith.MYDEALWITH_LIST;
      }
      if (reactiveData.activeName === "COMPLETED") {
        commit = api.myDealWith.MYDEALWITH_LISTD;
      }
      commit(reactiveData.filterData).then((res) => {
        if (res.code === 0) {
          reactiveData.listData = res.data.list;
          reactiveData.total = res.data.total;
        }
      });
    };

    const cancelOperation = (row) => {
      currentInstance.proxy
        .alertBox({ title: "撤销审批", message: "是否确认取消？" })
        .then(() => {
          handlTaskId(row?.currentTask?.taskId, row, 2);
        });
    };

    // 审批弹框
    const handlApproval = (val) => {
      if (reactiveData.userName === val.initiator) {
        reactiveData.boole = true;
      }
      handlTaskId(val?.currentTask?.taskId, val, 1);
    };

    const handlTaskId = (id, val, num) => {
      api.approval.APPROVAL_FORM({ taskId: id }).then((res) => {
        if (res.code === 0) {
          if (num === 1) {
            const currentTask = {
              form: res.data,
              taskId: id,
            };
            reactiveData.bouncedDialog.open(currentTask, val);
          } else {
            var form = {
              result: {
                type: String,
                value: null,
              },
            };
            form.result.value = "REPEAL";
            var dataList = {
              taskId: id,
              form: form,
            };
            api.approval.APPROVAL_SUBMIT(dataList).then((res) => {
              if (res.code === 0) {
                currentInstance.proxy.customMessage({
                  type: "success",
                  message: "撤销成功",
                });
                handlList();
              } else {
                currentInstance.proxy.customMessage({
                  type: "error",
                  message: res.msg,
                });
              }
            });
          }
        }
      });
    };

    //
    const succsess = () => {
      handlList();
    };

    const handlTime = (val) => {
      let str = "";
      const a = new Date();
      const b = new Date(val);
      const a1 = a.getTime();
      const b1 = b.getTime();
      const c = (a1 - b1) / 1000; // 时间差
      const d = parseInt(c / (24 * 60 * 60));
      const f = c % (24 * 60 * 60);
      const g = parseInt(f / 3600);
      if (d > 0) {
        str = `[滞留${d}天${g}小时]`;
      }
      return str;
    };

    // 排序
    const handlSort = (row) => {
      if (row.column) {
        if (row.column.label === "发起时间") {
          switch (row.order) {
            case "ascending":
              reactiveData.filterData.initiatorStart = "asc";
              break;
            case "descending":
              reactiveData.filterData.initiatorStart = "desc";
              break;
          }
          reactiveData.filterData.manageStartEnd = "";
        }

        if (row.column.label === "处理时间") {
          switch (row.order) {
            case "ascending":
              reactiveData.filterData.manageStartEnd = "asc";
              break;
            case "descending":
              reactiveData.filterData.manageStartEnd = "desc";
              break;
          }
          reactiveData.filterData.initiatorStart = "";
        }
      }
      handlList();
    };

    onMounted(() => {
      handlList();
     // handlHead();
    });
    return {
      ...toRefs(reactiveData),
      cellStyle,
      rowClick,
      handlReact,
      handlList,
      handleClick,
      handlApproval,
      succsess,
      handlSearch,
      handlDate,
      cancelOperation,
      handlTaskId,
      handlTime,
      handlSort,
    };
  },
};
</script>

<style>
</style>
